package com.hupu.jrs.ui.account

import android.app.Activity
import com.afollestad.materialdialogs.MaterialDialog
import com.hupu.jrs.components.storage.UserStorage
import com.hupu.jrs.injector.PerActivity
import com.hupu.jrs.otto.AccountChangeEvent
import com.squareup.otto.Bus
import javax.inject.Inject
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

/**
 * Created by sll on 2016/3/10.
 */
@PerActivity
class AccountPresenter @Inject
constructor(private val mUserDao: UserDao, private val mActivity: Activity, private val mUserStorage: UserStorage,
            private val mBus: Bus) : AccountContract.Presenter {

    private var mAccountView: AccountContract.View? = null
    private var mSubscription: Subscription? = null

    private fun loadUserList() {
        mSubscription = Observable.create<List<User>> { subscriber -> subscriber.onNext(mUserDao.queryBuilder().list()) }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { users -> mAccountView!!.renderUserList(users) }
    }

    override fun attachView(view: AccountContract.View) {
        mAccountView = view
        loadUserList()
    }

    override fun detachView() {
        if (mSubscription != null && !mSubscription!!.isUnsubscribed) {
            mSubscription!!.unsubscribe()
        }
        mAccountView = null
    }

    override fun onAccountDelClick(user: User) {
        MaterialDialog.Builder(mActivity).title("提示")
                .content("确认删除账号?")
                .positiveText("确定")
                .negativeText("取消")
                .callback(object : MaterialDialog.ButtonCallback() {
                    override fun onPositive(dialog: MaterialDialog?) {
                        mUserDao.delete(user)
                        if (String.valueOf(user.getUid()) == mUserStorage.getUid()) {
                            mUserStorage.logout()
                        }
                        mBus.post(AccountChangeEvent())
                        loadUserList()
                    }
                })
                .show()
    }

    override fun onAccountClick(user: User) {
        if (user.uid != mUserStorage.uid) {
            mUserStorage.login(user)
            mBus.post(AccountChangeEvent())
            mActivity.finish()
        }
    }
}
